package com.szxy.common.zuul.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Component;

/**
 * @Auther:zwer
 * @Date:2019/9/26 19:09
 * @Description:com.szxy.common.zuul.filter
 * @Version:1.0
 * 限流器
 **/
@Component
public class RateLimitFilter extends ZuulFilter {

    // 创建令牌桶
    //  RateLimiter.create(1) 是指每秒生成令牌的数量
    // 数值越大，表示处理请求的数量越多，数值越小代表处理请求的数量越少
    private final RateLimiter RATE_LIMIT = RateLimiter.create(1);

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE; //请求之前
    }

    // 限流器的优先级应为最高
    @Override
    public int filterOrder() {
        return FilterConstants.SERVLET_DETECTION_FILTER_ORDER - 1;
    }

    // 表示是否开启限流器， true 为开启，false 为关闭
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        if (!RATE_LIMIT.tryAcquire()) {
            RequestContext requestContext = RequestContext.getCurrentContext();
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(429);// Http 状态码429表示请求超时
            System.out.println("限流 ....");
        }
        return null;
    }
}
